package cc.c3p0.admin.common.dto;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.List;

/**
 * 通用的数据传输模型
 * Created by binchao on 2017/3/2.
 */
public class Json {
    private boolean success = false;

    /**
     * 状态码
     */
    private int code = 0;

    /**
     * 提示消息
     */
    private String msg;

    /**
     * 数据对象
     */
    private Object obj;

    public Json() {
        super();
    }

    public Json(String msg) {
        super();
        this.msg = msg;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getObj() {
        return obj;
    }

    public void setObj(Object obj) {
        this.obj = obj;
    }

    public String handleError(BindingResult result) {
        if(result.hasErrors()) {
            List<ObjectError> errList = result.getAllErrors();
            StringBuilder sb = new StringBuilder();
            for(ObjectError err : errList) {
                sb.append("[" + err.getDefaultMessage() + "]");
            }
            return sb.toString();
        }
        return null;
    }
}
